#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>
#include<stdlib.h>

typedef struct ListNode
{
    int val;
    struct ListNode* next;
}ListNode;

ListNode* DetectCycle(ListNode* head) {
    ListNode* slow = head;
    ListNode* fast = head;
    while (fast && fast->next)
    {
        slow = slow->next;
        fast = fast->next->next;
        if (slow == fast)
        {
            ListNode* start = head;
            ListNode* meet = slow;
            while (start != meet)
            {
                start = start->next;
                meet = meet->next;
            }
            return meet;
        }
    }
    return NULL;
}

ListNode* CreateList(int* num, int sz)
{
    ListNode* head = NULL;
    ListNode* tail = NULL;
    int i = 0;
    for (i = 0; i < sz; i++)
    {
        ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
        if (newnode == NULL)
        {
            perror("malloc:");
            return NULL;
        }
        newnode->next = NULL;
        newnode->val = num[i];
        if (head == NULL)
        {
            head = tail = newnode;
        }
        else
        {
            tail->next = newnode;
            tail = tail->next;
        }
    }
    tail->next = head->next;
    return head;
}

int main()
{
    int arr[] = { 3,2,0,-4 };
    int size = sizeof(arr) / sizeof(arr[0]);
    ListNode* phead = CreateList(arr, size);
    ListNode* start = DetectCycle(phead);
    printf("%d\n", start->val);
    return 0;
}